package com.plian.system.service.qg.subsidiary.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.constant.baseinfo.ValueSetConstant;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dto.qg.subsidiary.SubsidiaryIntroduceReformDTO;
import com.plian.system.entity.pm.property.PropertyBasics;
import com.plian.system.entity.qg.subsidiary.MixedOwnershipStructure;
import com.plian.system.entity.qg.subsidiary.SubsidiaryIntroduceReform;
import com.plian.system.mapper.qg.subsidiary.SubsidiaryIntroduceReformMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.pm.property.IPropertyBasicsService;
import com.plian.system.service.qg.subsidiary.IMixedOwnershipStructureService;
import com.plian.system.service.qg.subsidiary.ISubsidiaryIntroduceReformService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.qg.subsidiary.MixedOwnershipStructureVO;
import com.plian.system.vo.qg.subsidiary.SubsidiaryIntroduceReformVO;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.wrapper.qg.subsidiary.MixedOwnershipStructureWrapper;
import com.plian.system.wrapper.qg.subsidiary.SubsidiaryIntroduceReformWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 引进非市级国有资本 服务实现类
 *
 * @author jianglei
 * @since 2019-11-05
 */
@Slf4j
@Service
@AllArgsConstructor
public class SubsidiaryIntroduceReformServiceImpl extends BaseServiceImpl<SubsidiaryIntroduceReformMapper, SubsidiaryIntroduceReform> implements ISubsidiaryIntroduceReformService, BaseFlowService {

    private final FormWorkflowService formWorkflowService;

    private IFormCodeService formCodeService;

    private IMixedOwnershipStructureService mixedOwnershipStructureService;

    private BaseInfoService baseInfoService;

    private IPropertyBasicsService propertyBasicsService;

    private SubsidiaryIntroduceReformWrapper subsidiaryIntroduceReformWrapper;

    private MixedOwnershipStructureWrapper mixedOwnershipStructureWrapper;

    private FileService fileService;

    @Override
    public boolean saveOrUpdate(SubsidiaryIntroduceReform subsidiaryIntroduceReform) {

        if (subsidiaryIntroduceReform.getId() == null){
            subsidiaryIntroduceReform.setCode(formCodeService.getCode(FormTypeConstant.QG_SUBSIDIARY_INTRODUCE_FORM));
            subsidiaryIntroduceReform.setFormType(String.valueOf(FormTypeConstant.QG_SUBSIDIARY_INTRODUCE_FORM));
        }
        if (!Optional.ofNullable(subsidiaryIntroduceReform.getStatus()).isPresent()) {
            subsidiaryIntroduceReform.setStatus(FormStatusConstant.UNREVIEWED);
        }

        if (CollectionUtil.isNotEmpty(subsidiaryIntroduceReform.getMajorIndustryIds())){
            subsidiaryIntroduceReform.setMajorIndustryId(String.join(StringPool.COMMA, subsidiaryIntroduceReform.getMajorIndustryIds()));
        }
        if (CollectionUtil.isNotEmpty(subsidiaryIntroduceReform.getIntroduceCategoryIds())){
            subsidiaryIntroduceReform.setIntroduceCategoryId(String.join(StringPool.COMMA, subsidiaryIntroduceReform.getIntroduceCategoryIds()));
        }
        return super.saveOrUpdate(subsidiaryIntroduceReform);
    }

    @Override
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            SubsidiaryIntroduceReform subsidiaryIntroduceReform = getById(id);
            if (subsidiaryIntroduceReform == null) {
                return false;
            } else if (subsidiaryIntroduceReform.getStatus() != null &&
                    (subsidiaryIntroduceReform.getStatus() != FormStatusConstant.STASH && subsidiaryIntroduceReform.getStatus() != FormStatusConstant.UNREVIEWED)) {
                return false;
            }
            formWorkflowService.deleteProcessInstance(String.valueOf(id));
        }
        mixedOwnershipStructureService.deleteLogicByMixedReformId(ids);
        return super.deleteLogic(ids);
    }

    @Override
    public HashMap<String,Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String,Object>();
    }

    @Override
    public Boolean finish(String id) {
        /**
         * 设置审批人和审批时间
         */
        SubsidiaryIntroduceReform subsidiaryIntroduceReform = getById(id);
        subsidiaryIntroduceReform.setApprovedUser(TokenUtil.getTokenUserId());

        Date now = DateUtil.now();
        subsidiaryIntroduceReform.setApprovedTime(now);
        updateById(subsidiaryIntroduceReform);

        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
    }

    @Override
    public Boolean reject(String id, int formState, String comment) {
        return handleStatus(Long.valueOf(id), formState);
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<SubsidiaryIntroduceReform> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SubsidiaryIntroduceReform::getId, Func.toLongList(org.apache.commons.lang3.StringUtils.join(formIds, StringPool.COMMA)));
        List<SubsidiaryIntroduceReform> subsidiaryIntroduceReforms = list(queryWrapper);
        List<SubsidiaryIntroduceReformVO> subsidiaryIntroduceReformVOS = subsidiaryIntroduceReformWrapper.entityToVO(subsidiaryIntroduceReforms);
        List<PageData> pageDataList = new ArrayList<>();
        try{
            if (CollectionUtil.isNotEmpty(subsidiaryIntroduceReformVOS)){
                for (SubsidiaryIntroduceReformVO vo : subsidiaryIntroduceReformVOS){
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getCompanyName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getCompanyId());
                    pd.put("formType", FormTypeConstant.QG_SUBSIDIARY_INTRODUCE_FORM);
                    pd.put("orgName", vo.getCompanyName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.QG_SUBSIDIARY_INTRODUCE_FORM);
    }

    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED);
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public Boolean submit(SubsidiaryIntroduceReform subsidiaryIntroduceReform) {
        boolean result = saveOrUpdate(subsidiaryIntroduceReform);
        if (result){
            List<MixedOwnershipStructure> mixedOwnershipStructures = subsidiaryIntroduceReform.getMixedOwnershipStructures();
            if (CollectionUtil.isNotEmpty(mixedOwnershipStructures)){
                for (MixedOwnershipStructure mixedOwnershipStructure : mixedOwnershipStructures){
                    if (mixedOwnershipStructure.getId() != null &&
                            Optional.ofNullable(mixedOwnershipStructure.getIsDeleted()).isPresent() && mixedOwnershipStructure.getIsDeleted().intValue() == 1) {
                        mixedOwnershipStructureService.removeById(mixedOwnershipStructure.getId());
                    }else {
                        mixedOwnershipStructure.setMixedReformId(subsidiaryIntroduceReform.getId());
                        mixedOwnershipStructureService.saveOrUpdate(mixedOwnershipStructure);
                    }
                }
            }
            List<HashMap> listDoc = subsidiaryIntroduceReform.getList_doc();
            fileService.edit(subsidiaryIntroduceReform.getId().toString(),listDoc);
        }

        return result;
    }

    @Override
    public R<SubsidiaryIntroduceReformVO> getDetailObj(SubsidiaryIntroduceReformVO subsidiaryIntroduceReformVO) {
        if(!Optional.ofNullable(subsidiaryIntroduceReformVO).isPresent()){
            return new R(CommonCode.FAIL);
        }
        subsidiaryIntroduceReformVO.setMixedOwnershipStructureVOS(mixedOwnershipStructureWrapper.entityToVO(mixedOwnershipStructureService
                .list(new LambdaQueryWrapper<MixedOwnershipStructure>().eq(MixedOwnershipStructure::getMixedReformId, subsidiaryIntroduceReformVO.getId()))));
        R<SubsidiaryIntroduceReformVO> objResult = new R<>(CommonCode.SUCCESS);
        objResult.setPageData(subsidiaryIntroduceReformVO);
        return objResult;
    }

    @Override
    public ReportReturnVO introduceStatistics(SubsidiaryIntroduceReformDTO subsidiaryIntroduceReformDTO) {
        List<SubsidiaryIntroduceReformVO> subsidiaryMixedReformVOS = baseMapper.introduceStatisticsList(subsidiaryIntroduceReformDTO);
        List<SubsidiaryIntroduceReformVO> data = new ArrayList<>();

        if (!CollectionUtils.isEmpty(subsidiaryMixedReformVOS)){

            Map<String, String> allMap = baseInfoService.getChildMap(ValueSetConstant.ROOT);

            Map<String, List<SubsidiaryIntroduceReformVO>> map = subsidiaryMixedReformVOS.stream()
                    .filter(subsidiaryMixedReformVO -> Optional.ofNullable(subsidiaryMixedReformVO.getCreateCompanyName()).isPresent())
                    .collect(Collectors.groupingBy(SubsidiaryIntroduceReformVO::getCreateCompanyName));
            List<SubsidiaryIntroduceReformVO> sumList = new ArrayList<>();
            map.forEach((key, value) ->
            {
                data.addAll(value);
                SubsidiaryIntroduceReformVO sum = new SubsidiaryIntroduceReformVO();
                sum.setCompanyName("小计：" + value.size());
                for (SubsidiaryIntroduceReformVO vo : value){
                    List<MixedOwnershipStructure> mixedOwnershipStructures = vo.getMixedOwnershipStructures();
                    if (CollectionUtil.isNotEmpty(mixedOwnershipStructures)){
                        String str = "";
                        for (MixedOwnershipStructure mixedOwnershipStructure : mixedOwnershipStructures){
                            if (StringUtil.isNotBlank(str)){
                                str += " ，";
                            }
                            str += mixedOwnershipStructure.getShareholders() + ":" + mixedOwnershipStructure.getEquityRatio();
                        }
                        vo.setMixedOwnershipStructure(str);
                    }


                    if (StringUtil.isNotBlank(vo.getCompanyRankId()) && allMap.containsKey(vo.getCompanyRankId())) {
                        vo.setCompanyRankName(allMap.get(vo.getCompanyRankId()));
                    }

                    if (StringUtil.isNotBlank(vo.getMajorIndustryId())){
                        String[] majorIndustryIds = vo.getMajorIndustryId().split(",");
                        List<String> majorIndustryNames = new ArrayList<>();
                        for (String str : majorIndustryIds){
                            if (allMap.containsKey(str)){
                                majorIndustryNames.add(allMap.get(str));
                            }
                        }
                        vo.setMajorIndustryNames(majorIndustryNames);

                    }

                    if (StringUtil.isNotBlank(vo.getFunctionalCategoryId()) && allMap.containsKey(vo.getFunctionalCategoryId())) {
                        vo.setFunctionalCategoryName(allMap.get(vo.getFunctionalCategoryId()));
                    }

                    if (StringUtil.isNotBlank(vo.getIntroduceCategoryId()) && allMap.containsKey(vo.getIntroduceCategoryId())) {
                        vo.setIntroduceCategoryName(allMap.get(vo.getIntroduceCategoryId()));
                    }


                    sum.setIntroduceRegisteredCapital(BigDecimalUtil.add(sum.getIntroduceRegisteredCapital(), vo.getIntroduceRegisteredCapital()));
                    sum.setIntroduceCapitalAmount(BigDecimalUtil.add(sum.getIntroduceCapitalAmount(), vo.getIntroduceCapitalAmount()));
                }
                sumList.add(sum);
                data.add(sum);
            });

            SubsidiaryIntroduceReformVO end = new SubsidiaryIntroduceReformVO();
            end.setCompanyName("总计：" + subsidiaryMixedReformVOS.size());
            for (SubsidiaryIntroduceReformVO sum : sumList){
                end.setIntroduceRegisteredCapital(BigDecimalUtil.add(end.getIntroduceRegisteredCapital(), sum.getIntroduceRegisteredCapital()));
                end.setIntroduceCapitalAmount(BigDecimalUtil.add(end.getIntroduceCapitalAmount(), sum.getIntroduceCapitalAmount()));
            }
            data.add(end);
        }


        ReportReturnVO reportReturnVO = new ReportReturnVO();
        ReportVO reportVO = new ReportVO();

        reportVO
                .addHeader(HeaderVO.builder().key("companyName").title("填报单位").build())
                .addHeader(HeaderVO.builder().key("companyRankName").title("企业级次").build())
                .addHeader(HeaderVO.builder().key("majorIndustryNames").title("所属行业").build())
                .addHeader(HeaderVO.builder().key("functionalCategoryName").title("功能分类").build())
                .addHeader(HeaderVO.builder().key("implementationTime").title("首次混改日期").build())
                .addHeader(HeaderVO.builder().key("introduceCategoryName").title("引进方式").build())
                .addHeader(HeaderVO.builder().key("introduceRegisteredCapital").title("引进后注册资本(万元)").build())
                .addHeader(HeaderVO.builder().key("introduceCapitalAmount").title("引入非市级国有资本金额(万元)").build())
                .addHeader(HeaderVO.builder().key("subsidiaryNum").title("子企业数").build())
//                .addHeader(HeaderVO.builder().key("employeeStockRatio").title("员工持股比例%").build())
                .addHeader(HeaderVO.builder().key("mixedOwnershipStructure").title("混改后企业股权结构").build());

        reportVO.setData(data);
        reportReturnVO.setGrids(reportVO);
        return reportReturnVO;
    }

    @Override
    public ReportReturnVO introduceCapitalInfoReport(SubsidiaryIntroduceReformDTO subsidiaryIntroduceReformDTO) {
        QueryWrapper<SubsidiaryIntroduceReform> queryWrapper = new QueryWrapper<>();
        ReportReturnVO reportReturnVO = new ReportReturnVO();
        if(Optional.ofNullable(subsidiaryIntroduceReformDTO.getCompanyIds()).isPresent()){
            queryWrapper.in("create_company_id", subsidiaryIntroduceReformDTO.getCompanyIds());
        }
        if(StringUtil.isNoneBlank(subsidiaryIntroduceReformDTO.getCompanyName())){
            QueryWrapper propertyQueryWrapper=new QueryWrapper();
            propertyQueryWrapper.like("org_name",subsidiaryIntroduceReformDTO.getCompanyName());
            propertyQueryWrapper.eq("status",3);
            propertyQueryWrapper.eq("competent_organization", TokenUtil.getCompetentOrganization());
            List<PropertyBasics> propertyBasicsList=propertyBasicsService.list(propertyQueryWrapper);
            if(propertyBasicsList.size()==0){
                queryWrapper.eq("status", -1);
            }else{
                List<String> companyIds=propertyBasicsList.stream().map(record->record.getId()).collect(Collectors.toList());
                queryWrapper.in("company_id",companyIds);
            }
        }
        queryWrapper.eq("status", 3);

        if(StringUtil.isNoneBlank(subsidiaryIntroduceReformDTO.getMixedCategoryId())){
            queryWrapper.eq("mixed_category_id",subsidiaryIntroduceReformDTO.getMixedCategoryId());
        }
        if(StringUtil.isNoneBlank(subsidiaryIntroduceReformDTO.getFunctionalCategoryId())){
            queryWrapper.eq("functional_category_id",subsidiaryIntroduceReformDTO.getFunctionalCategoryId());
        }
        if(StringUtil.isNoneBlank(subsidiaryIntroduceReformDTO.getMixedModeId())){
            queryWrapper.eq("mixed_mode_id",subsidiaryIntroduceReformDTO.getMixedModeId());
        }
        if(CollectionUtil.isNotEmpty(subsidiaryIntroduceReformDTO.getIntroduceCategoryIds())){
            queryWrapper.in("introduce_category_id",subsidiaryIntroduceReformDTO.getIntroduceCategoryIds());
        }

        if(StringUtil.isNoneBlank(subsidiaryIntroduceReformDTO.getMixedType())){
            queryWrapper.eq("mixed_type",subsidiaryIntroduceReformDTO.getMixedType());
        }
        if(Optional.ofNullable(subsidiaryIntroduceReformDTO.getStartTime()).isPresent()){
            queryWrapper.ge("implementation_time",subsidiaryIntroduceReformDTO.getStartTime());
        }
        if(Optional.ofNullable(subsidiaryIntroduceReformDTO.getEndTime()).isPresent()){
            queryWrapper.le("implementation_time",subsidiaryIntroduceReformDTO.getEndTime());
        }
        List<SubsidiaryIntroduceReform> subsidiaryIntroduceReforms = list(queryWrapper);

        List<SubsidiaryIntroduceReformVO> tempData= subsidiaryIntroduceReformWrapper.entityToVO(subsidiaryIntroduceReforms);

        Map<String, SubsidiaryIntroduceReformVO> subsidiaryIntroduceReformVOMap=tempData.stream().collect(
                Collectors.groupingBy(record->record.getCompanyId(),Collectors.collectingAndThen(
                        Collectors.reducing((c1,c2)->c1.getUpdateTime().compareTo(c2.getUpdateTime())>=0?c1:c2),Optional::get)
                ));
        List<SubsidiaryIntroduceReformVO> data=new ArrayList<SubsidiaryIntroduceReformVO>(subsidiaryIntroduceReformVOMap.values());
        if (CollectionUtil.isNotEmpty(data)){
            for (SubsidiaryIntroduceReformVO subsidiaryIntroduceReformVO : data){
                subsidiaryIntroduceReformVO.setMixedOwnershipStructureVOS(mixedOwnershipStructureWrapper.entityToVO(mixedOwnershipStructureService
                        .list(new QueryWrapper<MixedOwnershipStructure>().eq("mixed_reform_id", subsidiaryIntroduceReformVO.getId()))));
                if (CollectionUtil.isNotEmpty(subsidiaryIntroduceReformVO.getMixedOwnershipStructureVOS())){
                    String mixedOwnershipStructuresFullStr="";
                    for (int i = 0; i < subsidiaryIntroduceReformVO.getMixedOwnershipStructureVOS().size(); i++){
                        MixedOwnershipStructureVO record = subsidiaryIntroduceReformVO.getMixedOwnershipStructureVOS().get(i);
                        record.setIndex(i + 1);
                        String shareholders = record.getShareholders();
                        String shareholdersNatureName = record.getShareholdersNatureName() == null ? "/" : record.getShareholdersNatureName();
                        BigDecimal equityRatio = record.getEquityRatio() == null ? new BigDecimal(0) : record.getEquityRatio();
                        String orgPaidCapital = record.getOrgPaidCapital() == null ? "/" : record.getOrgPaidCapital();
                        String orgSubscribedCapital = record.getOrgSubscribedCapital() == null ? "/" : record.getOrgSubscribedCapital();
                        mixedOwnershipStructuresFullStr += shareholders + "," + shareholdersNatureName + "," + equityRatio + "," + orgPaidCapital + "," + orgSubscribedCapital + ";";
                    }

                    subsidiaryIntroduceReformVO.setMixedOwnershipStructureFullStr(mixedOwnershipStructuresFullStr);
                    subsidiaryIntroduceReformVO.setStatusName("审批通过");
                }
            }
        }

        ReportVO reportVO = new ReportVO();

        reportVO
                .addHeader(HeaderVO.builder().key("code").title("单据编码").build())
                .addHeader(HeaderVO.builder().key("mixedEnterpriseName").title("混改企业名称").build())
                .addHeader(HeaderVO.builder().key("affiliatedOrgFullName").title("所属集团名称").build())
                .addHeader(HeaderVO.builder().key("companyRankName").title("企业级次").build())
                .addHeader(HeaderVO.builder().key("majorIndustryNames").title("所属行业").build())
                .addHeader(HeaderVO.builder().key("functionalCategoryName").title("功能分类").build())
                .addHeader(HeaderVO.builder().key("implementationTime").title("首次混改日期").build())
                .addHeader(HeaderVO.builder().key("mixedModeName").title("混改方式").build())
                .addHeader(HeaderVO.builder().key("mixedTypeName").title("混改类型").build())
                .addHeader(HeaderVO.builder().key("mixedCategoryName").title("企业类别").build())
                .addHeader(HeaderVO.builder().key("stateFundedRelationName").title("与国家出资企业关系").build())
                .addHeader(HeaderVO.builder().key("introduceRegisteredCapital").title("注册资本").build())
                .addHeader(HeaderVO.builder().key("subsidiaryNum").title("子企业数").build())
                .addHeader(HeaderVO.builder().key("introduceCapitalRatio").title("非市级国有资本占比%").build())
                .addHeader(HeaderVO.builder().key("introduceCapitalAmount").title("非市级国有资本金额").build())
//                .addHeader(HeaderVO.builder().key("employeeStockRatio").title("员工持股比例%").build())
//                .addHeader(HeaderVO.builder().key("employeeSharingholdingNums").title("员工持股人数").build())
                .addHeader(HeaderVO.builder().key("mixedOwnershipStructureFullStr").title("混改后企业股权结构").build());

        reportVO.setData(data);
        reportReturnVO.setGrids(reportVO);

        return reportReturnVO;
    }

    @Override
    public void exportDetailExcel(SubsidiaryIntroduceReformVO subsidiaryIntroduceReformVO, HttpServletResponse response) {
        try{
            String separator = File.separator;
            String exlPath = separator + "exceldemo" + separator + "introduceCapitalInfo.xlsx";
            InputStream inputStream = this.getClass().getResourceAsStream(exlPath);
            String fileName = URLEncoder.encode("引进非市级国有资本信息情况", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 设置响应头和客户端保存文件名
            response.setCharacterEncoding("utf-8");
            OutputStream outputStream = response.getOutputStream();// 取得输出流
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            String implementationTimeStr="";
            Date implementationTime=subsidiaryIntroduceReformVO.getImplementationTime();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            if(implementationTime!=null){
                implementationTimeStr=sdf.format(implementationTime);
                subsidiaryIntroduceReformVO.setImplementationTimeStr(implementationTimeStr);
            }
            excelWriter.fill(subsidiaryIntroduceReformVO, writeSheet);
            subsidiaryIntroduceReformVO.setMixedOwnershipStructureVOS(mixedOwnershipStructureWrapper.entityToVO(mixedOwnershipStructureService
                    .list(new QueryWrapper<MixedOwnershipStructure>().eq("mixed_reform_id", subsidiaryIntroduceReformVO.getId()))));
            if (CollectionUtil.isNotEmpty(subsidiaryIntroduceReformVO.getMixedOwnershipStructureVOS())){
                String mixedOwnershipStructuresFullStr="";
                for (int i = 0; i < subsidiaryIntroduceReformVO.getMixedOwnershipStructureVOS().size(); i++){
                    MixedOwnershipStructureVO record = subsidiaryIntroduceReformVO.getMixedOwnershipStructureVOS().get(i);
                    record.setIndex(i + 1);
                    String shareholders = record.getShareholders();
                    String shareholdersNatureName = record.getShareholdersNatureName() == null ? "/" : record.getShareholdersNatureName();
                    BigDecimal equityRatio = record.getEquityRatio() == null ? new BigDecimal(0) : record.getEquityRatio();
                    String orgPaidCapital = record.getOrgPaidCapital() == null ? "/" : record.getOrgPaidCapital();
                    String orgSubscribedCapital = record.getOrgSubscribedCapital() == null ? "/" : record.getOrgSubscribedCapital();
                    mixedOwnershipStructuresFullStr += shareholders + "," + shareholdersNatureName + "," + equityRatio + "," + orgPaidCapital + "," + orgSubscribedCapital + ";";
                }

                subsidiaryIntroduceReformVO.setMixedOwnershipStructureFullStr(mixedOwnershipStructuresFullStr);
                subsidiaryIntroduceReformVO.setStatusName("审批通过");
            }
            excelWriter.fill(new FillWrapper("t",subsidiaryIntroduceReformVO.getMixedOwnershipStructureVOS()),fillConfig, writeSheet);
            excelWriter.finish();
            inputStream.close();
            outputStream.close();
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
        }
    }

    /**
     * 统一处理状态机事件方法
     * @param id 主键
     * @param updateStatus 更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus) {
        try {
            SubsidiaryIntroduceReform subsidiaryIntroduceReform = getById(id);
            subsidiaryIntroduceReform.setStatus(updateStatus);
            updateById(subsidiaryIntroduceReform);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }
}
